// 引用用户模版数据
const User = require('../models/User');
const crypto = require('crypto');
const recommender  = require('./recommender');

const userController = {
    // 用户登录
    login: async function (req, res) {
        let username = req.body.name
        let password = req.body.pwd
        // 首先进行参数判断
        if (username.length == 0) {
            res.render('login', {
                'state': true,
                'msg': "请输入账户！"
            })
        } else if (password.length < 6) {
            res.render('login', {
                'state': true,
                'msg': "密码过短，至少6位！"
            })
        } else {
            // 登录测试
            try {
                let user = await User.verify(req.body.name)
                if (user == undefined) {
                    res.render('login', {
                        'state': true,
                        'msg': "账户不存在，请注册！"
                    })
                } else {
                    const juser = JSON.parse(JSON.stringify(user))
                    var md5 = crypto.createHash('md5');
                    const md5psd = md5.update(password).digest('hex')
                    if (md5psd == juser.psd) { // 成功登录
                        req.session.username=username
                        req.session.uid = juser.id // 记录uid
                        res.cookie("username", username, { maxAge: 60*60* 1000, httpOnly: true }) // 设置cookie
                        res.redirect('/index')
                    } else {
                        res.render('login', {
                            'state': true,
                            'msg': "密码错误！"
                        })
                    }
                }
            } catch (err) {
                console.log(err)
            }
        }
    },

    //用户注册
    register: async function (req, res) {
        // 参数判断
        if (req.body.name.length <= 3) {
            res.render('register', {
                'state': true,
                'msg': "请输入正确账户，长度大于3."
            })
        } else if (req.body.pwd.length < 6) {
            res.render('register', {
                'state': true,
                'msg': "密码过短！"
            })
        } else if (req.body.pwd != req.body.pwd2) {
            res.render('register', {
                'state': true,
                'msg': "两次密码不一致！"
            })
        } else {
            // 分析
            try {
                // 已经存在账号
                let user = await User.verify(req.body.name)
                if (user != undefined) {
                    res.render('register', {
                        'state': true,
                        'msg': "账户已存在，请登录！"
                    })
                } else { // 正常注册
                    var md5 = crypto.createHash('md5');
                    const md5psd = md5.update(req.body.pwd).digest('hex')
                    let state = await User.create(req.body.name, md5psd)
                    if (state !== undefined) {
                        res.render('login', {
                            state:true,
                            msg:'注册成功！'
                        })
                    }
                }
            } catch (err) {
                console.log(err)
            }
        }
    },
    
    // 添加用户收藏
    collect:async function(req, res){
        if (req.session.login){
            const mid = req.body.mid;
            const uid = req.session.uid;
            var collection = await User.verifyCol(uid, mid);
            if(collection!=undefined){
                res.send("已经收藏过了。");
            }else{
                let state = await User.collect(uid, mid);
                console.log(state);
                res.send("收藏成功。");
                recommender.update(req);
            }
        }else{
            res.send("请先登录。")
        }
    },
    uncollect: async function(req, res){
        if (req.session.login){
            const mid = req.body.mid;
            const uid = req.session.uid;
            var state = await User.deleteCol(uid, mid);
            res.send("取消收藏成功。");
            recommender.update(req);
        }else{
            res.send("请先登录。")
        }
    },

    // 评分
    rank: async function (req, res) {
        if(req.session.login){
            const mid = req.body.mid;
            const score = req.body.score;
            const uid = req.session.uid;

            var state = await User.verifyRank(uid, mid)
            if(state == undefined){  // 第一次评分
                var state = await User.insertRank(uid, mid, score)
            }else{  // 修改评分
                var state = await User.updateRank(uid, mid, score)
            }
        }else{
            res.send({
                errcode: -1,
                errmsg: '未登录'
            })
        }
    }
}

module.exports = userController;